package com.example.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// login interceptor
@PropertySource("classpath:config/application-config.properties")
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${validate_onceToken}")
    public int validateOnceToken;

    private final static List<String> NO_AUTHENTIC_PATH = new ArrayList<String>() {
        private static final long serialVersionUID = 1L;
        {
//            add("/sys/test/login");
        }
    };


    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        /*String requestUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String url = requestUri.substring(contextPath.length());
        if (NO_AUTHENTIC_PATH.contains(url)) { // 不拦截
            return true;
        } else if (null == requestUri) { // 请求路径异常 为null
            return false;
        } else if (-1 != requestUri.indexOf("/ser/") || -1 != requestUri.indexOf("/sys/")) {
            boolean flag = extraMethod(request, response);
            if (flag) {
                String userToken = request.getHeader("userToken");
                if (null != userToken && !"".equals(userToken)) {
                    SysUser temp = TokenUtil.getUserByToken(userToken);
                    if (null != temp) {
                        Map<String, Object> executionContextMap = Maps.newHashMap(4);
                        Response<SysUser> res = sysUserController.selectItem(temp.getUserId());
                        SysUserExtend sysUserExtend = sysUserExtendService.queryByPrimaryKey(temp.getUserId());
                        Map<String, Object> map = orgRegionVOService.getUserRegion(temp.getUserId());
                        if (map != null && map.size() > 0) {
                            String dsName = String.valueOf(map.get("dsName"));
                            Integer dsId = Integer.parseInt(String.valueOf(map.get("dsId"))) ;
                            Integer dsCj = Integer.parseInt(String.valueOf(map.get("dsCj")));
                            if (sysUserExtend != null) {
                                sysUserExtend.setDsName(dsName);
                                sysUserExtend.setDsId(dsId);
                                sysUserExtend.setDsCj(dsCj);
                            }
                        }
                        if(sysUserExtend!=null){
                            Map jsMap = sysUserExtendService.getJS(sysUserExtend.getBbdwId(),sysUserExtend.getDsCj(),sysUserExtend.getDsId());
                            if(jsMap!=null && jsMap.size()>0){
                                if(StringUtils.isNotEmpty(String.valueOf(jsMap.get("js")))){
                                    sysUserExtend.setDsJsId(Integer.parseInt(String.valueOf(jsMap.get("js"))));
                                }
                                if(StringUtils.isNotEmpty(String.valueOf(jsMap.get("mc")))){
                                    sysUserExtend.setDsJsName(String.valueOf(jsMap.get("mc")));
                                }
                            }
                        }

                        executionContextMap.put("userId", temp.getUserId());
                        executionContextMap.put("userName", temp.getUserName());
                        executionContextMap.put("userToken", userToken);
                        executionContextMap.put("sysUser", res.getData());
                        executionContextMap.put("sysUserExtend", sysUserExtend);
                        ExecutionContext.setExecutionContextMap(executionContextMap);
                    }
                }
            }
            return flag;
        }

        request.getRequestDispatcher("/public/index.html").forward(request, response);
        return false;*/
        return true;
    }
    /*private boolean checkOnceToken(String onceToken) {
        Response<Boolean> response = tokenController.checkOnceTokenValue(onceToken);
        if (response.isFlag()) {
            return response.getData();
        }
        return false;
    }

    private boolean checkSessionToken(String userToken) {
        if (StringUtils.isBlank(userToken)) {
            return false;
        }
        Response<Boolean> response = tokenController.checkSessionToken(userToken);
        if (response.isFlag()) {
            return response.getData();
        }
        return false;
    }*/

    /*public boolean extraMethod(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String url = request.getRequestURL().toString();
        if (url.contains("downloadTemplate") || url.contains("excelDerive")){
            return true;
        }
        String onceToken = request.getHeader("onceToken");
        String requestURI = request.getRequestURI();
        String userToken = request.getHeader("userToken");
        if (null != requestURI && -1 != requestURI.indexOf("getOnceTokenValue")) {
            return true;
        }
        //validateOnceToken==0不验证onceToken
        if (validateOnceToken > 0) {
            // 返回false 说明onceToken错误
            if (!checkOnceToken(onceToken)) {
                OutputStream outputStream = response.getOutputStream();
                response.setCharacterEncoding("UTF-8");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("flag", false);
                jsonObject.put("message", "check onceToken error!");
                jsonObject.put("code", 50012);
                outputStream.write(jsonObject.toJSONString().getBytes("UTF-8"));
                return false;
            }
        }

        if (null != requestURI && -1 != requestURI.indexOf("login")) {
            return true;
        }

        if (!checkSessionToken(userToken)) {
            OutputStream outputStream = response.getOutputStream();
            response.setCharacterEncoding("UTF-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("flag", false);
            jsonObject.put("message", "check userToken error!");
            jsonObject.put("code", 50014);
            outputStream.write(jsonObject.toJSONString().getBytes("UTF-8"));
            return false;
        }
        return true;
    }*/


}